<template>
  <t-card title="测试工具" :bordered="true" style="height: 100%; width: 100%;">
    <t-form ref="form" :data="formData" :rules="rules" @reset="onReset">
      <t-form-item label="服务器" name="server">
        <div style="display: flex; align-items: center; gap: 10px;">
          <t-space>
            <!-- 开启虚拟滚动 请为select的panel设定好height 通过popupProps进行透传 -->
            <t-select v-model="formData.server" :loading="serverLoading" :options="serverOptions.value" filterable
              placeholder="请选择" style="width: 300px" :scroll="{ type: 'virtual' }">
            </t-select>
          </t-space>
        </div>
      </t-form-item>
      <t-form-item label="uid" help="仅支持单个uid" name="uid">
        <t-input v-model="skillFormData.uid" style="width: 7%;"></t-input>
      </t-form-item>
    </t-form>

    <t-space direction="vertical">
      <t-card title="新手引导" bordered>
        <t-space>
          <template v-if="true">
            <t-button variant="outline" theme="primary"
              @click="SkillSubmit('beginner_tutorial_process')">跳过新手引导</t-button>
            <t-button variant="outline" theme="primary" @click="SkillSubmit('beginner_tutorial')">跳过新手引导（海外）</t-button>
          </template>
        </t-space>
      </t-card>

      <t-card title="段位" bordered>
        <t-space size="small" break-line>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 1000)">青铜V</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 1500)">白银V</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 2000)">黄金V</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 2500)">铂金V</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 3000)">钻石V</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 3500)">大师V</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 4000)">巅峰</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 4200)">巅峰菁英</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 4500)">巅峰宗师</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 4800)">巅峰战神</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('update_score', 5200)">巅峰至尊</t-button>
        </t-space>
      </t-card>
      <t-card title="模式" bordered>
        <t-space size="small" break-line>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('open_all_match_mode')">解锁全部模式</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('close_all_match_mode')">关闭全部模式</t-button>
        </t-space>
      </t-card>
      <t-card title="PVE" bordered>
        <t-space size="small" break-line>
          <t-button variant="outline" theme="primary"
            @click="SkillSubmit('unlock_all_pve_difficulty')">解锁全部难度</t-button>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('unlock_all_pve_handbook')">解锁全部图鉴</t-button>
        </t-space>
      </t-card>
      <t-card title="物品" bordered>
        <t-space size="small" break-line>
          <t-button variant="outline" theme="primary" @click="SkillSubmit('european')">欧洲人</t-button>
        </t-space>
      </t-card>
      <t-card title="时间" bordered>
        <t-space direction="vertical">
          <t-space size="small" break-line>
            <t-button variant="outline" theme="primary" @click="SkillSubmit('get_now_time')">获取服务器时间</t-button>
            <!-- 自定义格式（如 "YYYY年MM月DD日 HH:mm:ss"） -->
            <t-date-picker :value="server_time" format="YYYY-MM-DD HH:mm:ss" />

          </t-space>
          <t-space size="small" break-line>
            <t-button variant="outline" theme="primary" @click="SkillSubmit('set_now_time')">设置服务器时间</t-button>
            <t-date-picker enable-time-picker allow-input clearable v-model="setServerTime" />
          </t-space>

        </t-space>


      </t-card>
    </t-space>



  </t-card>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { useRouter } from 'vue-router';
import { fetchServerData, fetchItemData, RequestSendMail, RequestGodSkill } from '@/composables/usePax'
import { useServer } from '@/stores/pax.ts'
import { storeToRefs } from 'pinia'
const serverStore = useServer()
const { serverList } = storeToRefs(serverStore) // 保持响应式
const selectItems = ref([{ value: '', num: 1 }]); // 初始一个空选择器，带数量
const ItemLoading = ref(true);
const serverLoading = ref(true);
const sendLoading = ref(false);
const server_time = ref(null);
const setServerTime = ref(new Date());
const router = useRouter() // 获取路由实例
const formData = reactive({
  server: 's1',
  uids: [],
  mailType: 'sausage',
  num: 1,
});
const skillFormData = reactive({
  server: '',
  uid: '',
});

const rules = {
  server: [
    { required: true, message: '服务器必填', type: 'error', trigger: 'error' },
    { whitespace: true, message: '服务器不能为空' },
  ],
  uids: [
    { required: true, message: 'uid必填', type: 'error' },
    { whitespace: true, message: 'uid能为空' },
  ],
};


const options = ref([]); // 初始为空，稍后填充;
const serverOptions = ref([]); // 所有数据（缓存）

// 在组件加载时请求数据
onMounted(async () => {
  ItemLoading.value = true;
  try {
    // 获取 服务器 信息
    serverOptions.value = ref(serverList)

    // 获取 物品 信息
    const ItemData = await fetchItemData({ server: formData.server })

    if (formData.mailType === 'golddash') {
      options.value = ItemData.value.golddash_items;
    } else if (formData.mailType === 'sausage') {
      options.value = ItemData.value.sausage_items;
    }
    2
  } catch (error) {
    MessagePlugin.error('物品加载失败');
    setTimeout(() => {
      router.push('/login'), 1000
    })
  } finally {
    ItemLoading.value = false;
    serverLoading.value = false
  }
});
// 在 onMounted 之后添加监听逻辑
watch(
  () => formData.mailType,  // 监听 mailType 的变化
  (newMailType) => {
    // 1. 立即清空 options（避免显示旧数据）
    options.value = []; // 清空选项
    selectItems.value = [{ value: '', num: 1 }]; // 重置为初始状态（一个空选择器）
    // 当 mailType 变化时，重新请求接口
    fetchItemsByMailType(newMailType);
  }
);

// 定义请求函数
const fetchItemsByMailType = async (mailType) => {
  ItemLoading.value = true;
  try {
    const ItemData = await fetchItemData({ server: formData.server })
    if (mailType === 'golddash') {
      options.value = ItemData.value.golddash_items; // 更新为打金邮件数据
    } else if (mailType === 'sausage') {
      options.value = ItemData.value.sausage_items; // 更新为吃鸡邮件数据
    }

  } catch (error) {
    console.log('rrre', error)
    MessagePlugin.error('加载选项失败，请稍后重试');
  } finally {
    ItemLoading.value = false;
  }
};


const onReset = () => {

  // 2. 手动设置 mailType 的默认值
  formData.mailType = 'sausage'; // 默认勾选"吃鸡邮件"

  // 3. 可选：重置其他数据（如 selectItems）
  selectItems.value = [{ value: '', num: 1 }];
  MessagePlugin.success('重置成功');
};
const formatDateForBackend = (date) => {
  return Math.floor(date.getTime() / 1000)  // 转为秒级（10 位）
}
const SkillSubmit = async (query_key, score = null) => {
  console.log('这是query_key:', query_key)
  if (query_key == "get_now_time" || query_key == "set_now_time") {
    // 验证是否选择了服务器
    if (!formData.server) {
      MessagePlugin.error('请先选择服务器！')  // 提示用户
      return  // 终止执行
    }
  }
  const res = await RequestGodSkill(
    {
      server_name: formData.server,
      uid: skillFormData.uid,
      query_key,
      score,
      set_time: setServerTime.value
    }
  )
  const data = res.value;
  if (data.success) {
    if (query_key == "get_now_time") {
      server_time.value = data.data
    }
    MessagePlugin.success('执行成功');
  } else {
    MessagePlugin.error('执行失败');
  }
}

</script>
<style scoped>
</style>
